package com.txsj.scan.activity.allocationapply;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.txsj.scan.R;
import com.txsj.scan.adapter.AllocationBatchAdapter;
import com.txsj.scan.base.BaseActivity;
import com.txsj.scan.bean.AllocationApplyDetailsBean;
import com.txsj.scan.bean.AllocationBatchBean;
import com.txsj.scan.bean.EventAllocationBean;
import com.txsj.scan.presenter.AllocationBatchPresenter;
import com.txsj.scan.refresh.XRefreshView;
import com.txsj.scan.utils.GsonFactory;
import com.txsj.scan.utils.SoftInputUtils;
import com.txsj.scan.utils.glide.GlideImgManager;
import com.txsj.scan.view.IAllocationBatchView;
import com.txsj.scan.widget.TSnackbarView;
import com.txsj.scan.widget.TitleBarView;
import com.txsj.scan.widget.dialog.InputNumberDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * 调拨申请单  选择调拨批次页面
 */

public class AllocationBatchActivity extends BaseActivity<AllocationBatchPresenter> implements IAllocationBatchView, View.OnClickListener {
    @Override
    protected AllocationBatchPresenter providePresenter() {
        return new AllocationBatchPresenter(this);
    }

    @Override
    public Context context() {
        return this;
    }

    TitleBarView mTitle;
    ImageView iv_goods_pic;
    TextView tv_goods_name, tv_goods_stockCount;
    TextView tv_goods_num;
    XRefreshView xRefreshView;
    RecyclerView recyclerView;
    Button btn_skip, btn_next;

    AllocationBatchAdapter adapter;
    AllocationApplyDetailsBean detailsBean;
    List<AllocationBatchBean> batchList;
    private int goodsPosition = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_allocation_batch);
        initView();
        initData();
    }

    private void initData() {
        EventBus.getDefault().register(this);
        String goodData = getIntent().getStringExtra("detailsBean");
        if (!TextUtils.isEmpty(goodData)) {
            detailsBean = GsonFactory.parseJsonWithGson(goodData, AllocationApplyDetailsBean.class);
            if (detailsBean != null && detailsBean.getDetails().size() > 0) {
                setGoodsAndBatchData(goodsPosition);
            }
        }
    }

    AllocationApplyDetailsBean.DetailsBean goodsBean;

    private void setGoodsAndBatchData(int position) {
        if ((detailsBean.getDetails().size() - 1) >= position) {
            goodsBean = detailsBean.getDetails().get(position);
            GlideImgManager.getLoadRoundImg(this, goodsBean.getGoods_img(), iv_goods_pic);
            tv_goods_name.setText(goodsBean.getGoods_name());
            if (goodsBean.getGoods_num() != null) {
                tv_goods_num.setText(goodsBean.getGoods_num() + "");
            }

            tv_goods_stockCount.setText("库存：" + goodsBean.getPast_inventory());
            xRefreshView.startRefresh();

            if ((detailsBean.getDetails().size() - 1) > position) {
                btn_next.setText("下一个");
                btn_skip.setText("跳过");
            } else {
                btn_next.setText("完成");
                btn_skip.setText("暂无更多");
            }
        }
    }

    private void initView() {
        mTitle = (TitleBarView) findViewById(R.id.mTitle);
        iv_goods_pic = (ImageView) findViewById(R.id.iv_goods_pic);
        tv_goods_name = (TextView) findViewById(R.id.tv_goods_name);
        tv_goods_num = (TextView) findViewById(R.id.tv_goods_num);
        tv_goods_stockCount = (TextView) findViewById(R.id.tv_goods_stockCount);

        xRefreshView = (XRefreshView) findViewById(R.id.xRefreshView);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        btn_skip = (Button) findViewById(R.id.btn_skip);
        btn_skip.setOnClickListener(this);
        btn_next = (Button) findViewById(R.id.btn_next);
        btn_next.setOnClickListener(this);

        RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        adapter = new AllocationBatchAdapter(this);
        recyclerView.setAdapter(adapter);
        initEmptyView();
        xRefreshView.enableEmptyView(true);
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setAutoLoadMore(false);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                super.onRefresh(isPullDown);
                if (goodsBean != null) {
                    presenter.getAllocationBatchList("0", goodsBean.getGs1_num());
                } else {
                    xRefreshView.stopRefresh();
                }
            }
        });
        adapter.setChangeListener(new AllocationBatchAdapter.OnEditTextChangeListener() {
            @Override
            public void onClick(final int position) {
                InputNumberDialog dialog = new InputNumberDialog(AllocationBatchActivity.this);
                dialog.initData(batchList.get(position).getChange_num());
                dialog.setListener(new InputNumberDialog.OnOkChangeListener() {
                    @Override
                    public void onChange(long count) {
                        // 先隐藏键盘
                        SoftInputUtils.hideSoftInput(AllocationBatchActivity.this);
                        int oldNum = batchList.get(position).getGoods_count();
                        if (count <= oldNum) {
                            batchList.get(position).setChange_num(count);
                            adapter.notifyDataSetChanged();
                        } else {
                            showErrorMsg("该批次库存不足");
                        }
                    }
                });
                dialog.show();
            }

            @Override
            public void onDecrease(int position) {
                long count = batchList.get(position).getChange_num();
                if (count > 0) {
                    batchList.get(position).setChange_num(--count);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onIncrease(int position) {
                int oldNum = batchList.get(position).getGoods_count();
                long count = batchList.get(position).getChange_num();
                if (count < oldNum) {
                    batchList.get(position).setChange_num(++count);
                    adapter.notifyDataSetChanged();
                } else {
                    showErrorMsg("该批次库存不足");
                }
            }

            @Override
            public void onDelete(int position) {
                batchList.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
    }


    public void showErrorMsg(String msg) {
        new TSnackbarView(tv_goods_name, msg);
    }

    @Override
    public void loadBatchSuccess(List<AllocationBatchBean> dataList) {
        xRefreshView.stopRefresh();
        if (null == dataList || dataList.size() == 0) {
            return;
        }
        xRefreshView.enableEmptyView(false);
        batchList = dataList;
        adapter.setList(batchList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void loadFailed(String errMsg) {
        new TSnackbarView(mTitle, errMsg);
        xRefreshView.stopRefresh();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_skip:
                if ((detailsBean.getDetails().size() - 1) > goodsPosition) {
                    ++goodsPosition;
                    setGoodsAndBatchData(goodsPosition);
                }
                break;
            case R.id.btn_next:
                detailsBean.getDetails().get(goodsPosition).setBatchList(batchList);
                if (detailsBean.getDetails().size() - 1 > goodsPosition) {
                    ++goodsPosition;
                    if ((detailsBean.getDetails().size() - 1) >= goodsPosition) {
                        setGoodsAndBatchData(goodsPosition);
                    } else {
                        boolean isHave = false;
                        for (int i = 0; i < detailsBean.getDetails().size(); i++) {
                            for (int j = 0; j < detailsBean.getDetails().get(i).getBatchList().size(); j++) {
                                if (detailsBean.getDetails().get(i).getBatchList().get(j).getChange_num() > 0) {
                                    isHave = true;
                                }
                            }
                        }

                        if (!isHave) {
                            showErrorMsg("请设置调拨数量");
                            return;
                        }

                        //进行下一步 调拨提交
                        Intent intent = new Intent(AllocationBatchActivity.this, AllocationCheckStatusActivity.class);
                        intent.putExtra("detailsBean", new Gson().toJson(detailsBean));
                        startActivity(intent);
                    }
                } else {
                    boolean isHave = false;
                    for (int i = 0; i < detailsBean.getDetails().size(); i++) {
                        for (int j = 0; j < detailsBean.getDetails().get(i).getBatchList().size(); j++) {
                            if (detailsBean.getDetails().get(i).getBatchList().get(j).getChange_num() > 0) {
                                isHave = true;
                            }
                        }
                    }
                    if (!isHave) {
                        showErrorMsg("请设置调拨数量");
                        return;
                    }
                    //进行下一步 调拨提交
                    Intent intent = new Intent(AllocationBatchActivity.this, AllocationCheckStatusActivity.class);
                    intent.putExtra("detailsBean", new Gson().toJson(detailsBean));
                    startActivity(intent);
                }
                break;
        }
    }


    Button btn_empty_reload;

    /**
     * 列表数据为空时 显示的View
     */
    private void initEmptyView() {
        View emptyView = View.inflate(this, R.layout.view_empty, null);
        btn_empty_reload = (Button) emptyView.findViewById(R.id.btn_empty_reload);
        xRefreshView.setEmptyView(emptyView);
        btn_empty_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xRefreshView.startRefresh();
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(EventAllocationBean message) {
        if (message.isRefresh()) {
            this.finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
